package com.jqk.apipassener.controller;

import com.jqk.apipassener.feign.ProviderFeign;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @Author:jiangqikun
 * @Date:2022/3/11 18:56
 **/

@RestController
@Log4j2(topic = "ConsumerController")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ProviderFeign providerFeign;

    /**
     * RestTemplate 调用
     */
    @GetMapping("/rest-message")
    public String getMessageByRestTemplate(){
        String serviceName ="service-provider";
        String url ="http://"+ serviceName +"/send-message";
        String result = restTemplate.getForObject(url, String.class);
        log.debug("使用 RestTemplate + ribbon 掉用服务的结果是：{}",result);
        return  result;
    }

    /**
     * Feign 调用
     */
    @GetMapping("/feign-message")
    public String getMessageByFeign(){
        String result = providerFeign.sendMessage();
        log.debug("feign 掉用服务的结果是：{}",result);
        return  result;
    }


    /**
     * RestTemplate 测试 Hystrix+
     */
    @GetMapping("/rest-Hystrix")
    @HystrixCommand(fallbackMethod = "sendFail")
    public String getMessage2ByRestTemplate(){
        String serviceName ="service-provider";
        String url ="http://"+ serviceName +"/test-hystrix";
        String result = restTemplate.getForObject(url, String.class);
        log.debug("使用 RestTemplate + ribbon 掉用服务的结果是：{}",result);
        return  result;
    }

    /**
     * 降级方法：此方法的 请求参数和 返回参数 要和原方法一致。
     */
    private String sendFail(){
      return "调用服务失败，熔断";
    }


    /**
     * Feign 测试 Hystrix
     */
    @GetMapping("/feign-Hystrix")
    public String getMessage2ByFeign(){
        return providerFeign.testHystrix();
    }

    /**
     * Feign 测试超时重试
     */
    @GetMapping("/feign-time")
    public String getMessage3ByFeign(){return providerFeign.testTime();}
}
